<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备ID" prop="deviceId">
        <el-input
          v-model="queryParams.deviceId"
          placeholder="请输入设备ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="家庭ID" prop="familyId">
        <el-input
          v-model="queryParams.familyId"
          placeholder="请输入家庭ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据来源" prop="dataSource">
        <el-select v-model="queryParams.dataSource" placeholder="请选择数据来源" clearable>
          <el-option label="传感器" value="sensor" />
          <el-option label="手动输入" value="manual" />
          <el-option label="系统计算" value="system" />
        </el-select>
      </el-form-item>
      <el-form-item label="记录时间">
        <el-date-picker
          v-model="daterangeRecordTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['environment:monitor:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['environment:monitor:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['environment:monitor:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['environment:monitor:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 环境数据统计卡片 -->
    <el-row :gutter="20" class="mb8">
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>温度</span>
          </div>
          <div class="text item">
            <i class="el-icon-thermometer" style="color: #ff6b6b;"></i>
            <span class="value">{{ avgTemperature }}°C</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>湿度</span>
          </div>
          <div class="text item">
            <i class="el-icon-heavy-rain" style="color: #4ecdc4;"></i>
            <span class="value">{{ avgHumidity }}%</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>空气质量</span>
          </div>
          <div class="text item">
            <i class="el-icon-view" style="color: #45b7d1;"></i>
            <span class="value">{{ avgAirQuality }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>PM2.5</span>
          </div>
          <div class="text item">
            <i class="el-icon-warning" style="color: #f7b731;"></i>
            <span class="value">{{ avgPm25 }} μg/m³</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="monitorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="监控ID" align="center" prop="monitorId" />
      <el-table-column label="设备ID" align="center" prop="deviceId" />
      <el-table-column label="家庭ID" align="center" prop="familyId" />
      <el-table-column label="温度(°C)" align="center" prop="temperature" />
      <el-table-column label="湿度(%)" align="center" prop="humidity" />
      <el-table-column label="空气质量" align="center" prop="airQuality" />
      <el-table-column label="光照强度" align="center" prop="lightIntensity" />
      <el-table-column label="噪音等级" align="center" prop="noiseLevel" />
      <el-table-column label="PM2.5" align="center" prop="pm25" />
      <el-table-column label="CO2浓度" align="center" prop="co2Level" />
      <el-table-column label="数据来源" align="center" prop="dataSource" />
      <el-table-column label="记录时间" align="center" prop="recordTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['environment:monitor:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['environment:monitor:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改环境监控对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备ID" prop="deviceId">
              <el-input v-model="form.deviceId" placeholder="请输入设备ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="家庭ID" prop="familyId">
              <el-input v-model="form.familyId" placeholder="请输入家庭ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="温度(°C)" prop="temperature">
              <el-input v-model="form.temperature" placeholder="请输入温度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="湿度(%)" prop="humidity">
              <el-input v-model="form.humidity" placeholder="请输入湿度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="空气质量" prop="airQuality">
              <el-input v-model="form.airQuality" placeholder="请输入空气质量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="光照强度" prop="lightIntensity">
              <el-input v-model="form.lightIntensity" placeholder="请输入光照强度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="噪音等级" prop="noiseLevel">
              <el-input v-model="form.noiseLevel" placeholder="请输入噪音等级" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="PM2.5" prop="pm25">
              <el-input v-model="form.pm25" placeholder="请输入PM2.5" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="CO2浓度" prop="co2Level">
              <el-input v-model="form.co2Level" placeholder="请输入CO2浓度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据来源" prop="dataSource">
              <el-select v-model="form.dataSource" placeholder="请选择数据来源">
                <el-option label="传感器" value="sensor" />
                <el-option label="手动输入" value="manual" />
                <el-option label="系统计算" value="system" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker clearable
            v-model="form.recordTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择记录时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMonitor, getMonitor, delMonitor, addMonitor, updateMonitor } from "@/api/environment/monitor";

export default {
  name: "EnvMonitor",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 环境监控表格数据
      monitorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 记录时间时间范围
      daterangeRecordTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        familyId: null,
        dataSource: null,
        recordTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceId: [
          { required: true, message: "设备ID不能为空", trigger: "blur" }
        ],
        familyId: [
          { required: true, message: "家庭ID不能为空", trigger: "blur" }
        ],
      },
      // 统计数据
      avgTemperature: 0,
      avgHumidity: 0,
      avgAirQuality: 0,
      avgPm25: 0
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询环境监控列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeRecordTime && '' != this.daterangeRecordTime) {
        this.queryParams.params["beginRecordTime"] = this.daterangeRecordTime[0];
        this.queryParams.params["endRecordTime"] = this.daterangeRecordTime[1];
      }
      listMonitor(this.queryParams).then(response => {
        this.monitorList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.calculateAverage();
      });
    },
    // 计算平均值
    calculateAverage() {
      if (this.monitorList.length > 0) {
        const total = this.monitorList.length;
        let tempSum = 0, humSum = 0, airSum = 0, pmSum = 0;
        
        this.monitorList.forEach(item => {
          tempSum += parseFloat(item.temperature || 0);
          humSum += parseFloat(item.humidity || 0);
          airSum += parseFloat(item.airQuality || 0);
          pmSum += parseFloat(item.pm25 || 0);
        });
        
        this.avgTemperature = (tempSum / total).toFixed(1);
        this.avgHumidity = (humSum / total).toFixed(1);
        this.avgAirQuality = (airSum / total).toFixed(1);
        this.avgPm25 = (pmSum / total).toFixed(1);
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        monitorId: null,
        deviceId: null,
        familyId: null,
        temperature: null,
        humidity: null,
        airQuality: null,
        lightIntensity: null,
        noiseLevel: null,
        pm25: null,
        co2Level: null,
        recordTime: null,
        dataSource: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeRecordTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.monitorId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加环境监控";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const monitorId = row.monitorId || this.ids
      getMonitor(monitorId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改环境监控";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.monitorId != null) {
            updateMonitor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMonitor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const monitorIds = row.monitorId || this.ids;
      this.$modal.confirm('是否确认删除环境监控编号为"' + monitorIds + '"的数据项？').then(function() {
        return delMonitor(monitorIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('environment/monitor/export', {
        ...this.queryParams
      }, `monitor_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}
.text {
  font-size: 14px;
}
.item {
  padding: 18px 0;
  text-align: center;
}
.value {
  font-size: 24px;
  font-weight: bold;
  margin-left: 10px;
}
</style>